<template>
  <div class="all">
    <el-container class="all_content">
      <Sidebar />
      <el-container class="all_main">
        <el-header class="head">
          <el-breadcrumb separator="/">
            <el-breadcrumb-item class="item"><span class="t">教练列表</span></el-breadcrumb-item>
          </el-breadcrumb>
        </el-header>
        <el-main class="main">
          <div class="search-area">
            <div class="s">
              <el-input
                  v-model="searchForm.keyword"
                  placeholder="输入手机号、昵称或用户名搜索"
                  clearable
                  style="width: 1000px; height:40px;"
                  @keyup.enter="fetchCoaches"
              >
                <template #append>
                  <el-button @click="fetchCoaches">  搜索  </el-button>
                </template>
              </el-input>
              <el-select
                  v-model="selectedSortBy"
                  placeholder="选择排序方式"
                  style="width: 200px; margin-left: 10px;"
                  @change="handleSortTypeChange"
              >
                <el-option label="&nbsp;按创建时间排序" value="create_time" />
                <el-option label="&nbsp;按活跃度排序" value="activity_level" />
              </el-select>
            </div>

          </div>
          <div class="table-wrapper" style="width: 100%;">
            <el-table
                :data="CoachesList"
                border
                style="width: 90%;font-family: 'monospace';"
                :default-sort="{ prop: 'createTime', order: 'descending' }"
                @sort-change="handleSortChange"
                v-loading="loading"
                element-loading-text="数据加载中..."
            >
              <el-table-column type="index" label="序号" min-width="50" />
              <el-table-column prop="username" label="姓名" min-width="100" />
              <el-table-column prop="phone" label="手机号" min-width="120" />
              <el-table-column label="创建时间" min-width="120">
                <template #default="scope">
                  {{ formatCreateTime(scope.row.createTime) }}
                </template>
              </el-table-column>
              <el-table-column prop="fromApp" label="Web/APP" min-width="70">
                <template #default="scope">
                  {{ scope.row.fromApp === false ? 'Web' : 'APP' }}
                </template>
              </el-table-column>
              <el-table-column label="操作" min-width="170">
                <template #default="scope">
                  <el-button plain @click="open(scope.row)" width="110" style="display: inline-block;">
                    &nbsp;查看详情&nbsp;
                  </el-button>
                  <el-button plain @click="editCoach(scope.row)" width="110" style="display: inline-block;">
                    &nbsp;编辑信息&nbsp;
                  </el-button>
                  <el-button
                      plain
                      @click="resetPassword(scope.row)"
                      width="110"
                      style="display: inline-block;"
                  >
                    &nbsp;重置密码&nbsp;
                  </el-button>
                </template>
              </el-table-column>

              <el-table-column
                  prop="activity"
                  label="活跃度"
                  min-width="120"
              >
                <template #default="scope">
                  <el-progress
                      :percentage="calculateActivityPercentage(scope.row.activity)"
                      :stroke-width="16"
                      :status="getStatus(scope.row.activity)"
                      :text-inside="true"
                  />
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="pagination" style="padding: 20px 0 0 90px;">
            <el-pagination
                background
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[5,10, 20, 30]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
            />
          </div>
        </el-main>
      </el-container>
    </el-container>
    <!--编辑教练详情弹窗-->
    <el-dialog
        v-model="editDialogVisible"
        title="编辑教练信息"
        width="600px"
        @close="resetEditForm"
        @before-close="beforeCloseEditDialog"
    >
        <el-form :model="editForm" label-width="120px">
          <el-form-item label="姓名" prop="username" style="margin-bottom: 5px">
            <el-input v-model="editForm.username" />
          </el-form-item>

          <el-form-item label="UUID" prop="uuid" style="margin-bottom: 5px">
            <el-row :gutter="10">
              <el-col :span="16">
                <el-input
                    v-model="editForm.uuid"
                    placeholder="加载中..."
                    style="width: 370px"
                />
              </el-col>
              <el-col :span="8">
                <el-button
                    type="primary"
                    @click="copyUUID"
                    :disabled="!editForm.uuid"
                    style="margin-left: 70px;"
                >
                  <template v-if="copyStatus === 'copy'">
                    <CopyDocument /> &nbsp;复制UUID&nbsp;
                  </template>
                  <template v-else>
                    <Check /> &nbsp;已复制&nbsp;
                  </template>
                </el-button>
              </el-col>
            </el-row>
          </el-form-item>

          <el-form-item label="手机号" prop="phone" style="margin-bottom: 5px">
            <el-input v-model="editForm.phone" />
          </el-form-item>
          <el-form-item label="口号" prop="slogan" style="margin-bottom: 5px">
            <el-input v-model="editForm.slogan" />
          </el-form-item>
          <el-form-item label="驾校名称" prop="schoolName" style="margin-bottom: 5px">
            <el-input v-model="editForm.schoolName" />
          </el-form-item>
          <el-form-item label="地区选择" prop="regionCode" style="margin-bottom: 5px;">
            <el-select
                v-model="editForm.regionCode"
                placeholder="请选择地区"
                @change="handleRegionChange"
                clearable
            >
              <el-option
                  v-for="region in regionList"
                  :key="region.regionCode"
                  :label="region.name"
                  :value="region.regionCode"
                  style="margin-left: 10px;"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="备注" prop="notes" style="margin-bottom: 5px">
            <el-input v-model="editForm.notes" />
          </el-form-item>
          <el-form-item label="有效期" prop="validTime" style="margin-bottom: 5px">
            <el-date-picker
                v-model="editForm.validTime"
                type="date"
                placeholder="选择日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item label="分成比例" prop="ratio" >
            <el-input-number
                v-model="editForm.ratio"
                :min="0"
                :max="100"
                step="1"
                placeholder="请输入百分比"
                style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="是否属于管理员" prop="isBelongWithAdmin">
            <el-switch
                v-model="editForm.isBelongWithAdmin"
                active-text="是"
                inactive-text="否"
            />
          </el-form-item>
          <el-form-item label="是否主播" prop="isStreamer">
            <el-switch
                v-model="editForm.isStreamer"
                active-text="是"
                inactive-text="否"
            />
          </el-form-item>


          <el-form-item label="当前LOGO" style="margin-bottom: 5px;">
            <template #default>
              <div v-if="editForm.logo" class="logo-preview">
                <img
                    :src="editForm.logo"
                    alt="教练LOGO"
                    style="width: 120px; height: 120px; object-fit: cover; border-radius: 4px;"
                >
              </div>
              <div v-else class="logo-placeholder">
                <span style="color: #999;">未设置LOGO</span>
              </div>
            </template>
          </el-form-item>

          <el-form-item label="上传新LOGO" style="margin-bottom: 5px;">
            <el-upload
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                :before-upload="beforeUpload"
                :on-success="handleLogoUploadSuccess"
                :http-request="customLogoUpload"
            >
              <img
                  v-if="tempLogoUrl"
                  :src="tempLogoUrl"
                  class="avatar"
                  style="width: 120px; height: 120px; object-fit: cover; cursor: pointer;"
              >
              <el-icon v-else class="avatar-uploader-icon" style="width: 120px; height: 120px;">
                <Plus />
              </el-icon>
            </el-upload>
            <div style="margin-top: 8px; font-size: 12px; color: #666;">
              支持JPG、PNG格式，文件大小不超过2MB
            </div>
          </el-form-item>

          <el-form-item label="当前二维码" style="margin-bottom: 5px;">
            <template #default>
              <div v-if="editForm.qrCode" class="logo-preview">
                <img
                    :src="editForm.qrCode"
                    alt="教练二维码"
                    style="width: 120px; height: 120px; object-fit: cover; border-radius: 4px;"
                >
              </div>
              <div v-else class="logo-placeholder">
                <span style="color: #999;">未设置二维码</span>
              </div>
            </template>
          </el-form-item>
          <el-form-item label="上传二维码" style="margin-bottom: 5px;">
            <el-upload
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                :before-upload="beforeUpload"
                :on-success="handleQrcodeUploadSuccess"
                :http-request="customQrcodeUpload"
            >
              <img
                  v-if="tempQrcodeUrl"
                  :src="tempQrcodeUrl"
                  class="avatar"
                  style="width: 120px; height: 120px; object-fit: cover; cursor: pointer;"
              >
              <el-icon v-else class="avatar-uploader-icon" style="width: 120px; height: 120px;">
                <Plus />
              </el-icon>
            </el-upload>
            <div style="margin-top: 8px; font-size: 12px; color: #666;">
              支持JPG、PNG格式，文件大小不超过2MB
            </div>
          </el-form-item>
        </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">&nbsp;&nbsp;取消&nbsp;&nbsp;</el-button>
          <el-button type="primary" @click="saveCoach">&nbsp;&nbsp;保存&nbsp;&nbsp;</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 重置密码弹窗 -->
    <el-dialog
        v-model="resetPwdDialogVisible"
        title="重置教练密码"
        width="400px"
        :close-on-click-modal="false"
    >
      <el-form :model="resetPwdForm" label-width="100px" :rules="resetPwdRules" ref="resetPwdFormRef">
        <el-form-item label="新密码" prop="newPassword">
          <el-input
              v-model="resetPwdForm.newPassword"
              type="password"
              placeholder="请输入6-20位密码"
              show-password
              style="margin-bottom: 10px"
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
              v-model="resetPwdForm.confirmPassword"
              type="password"
              placeholder="请再次输入密码"
              show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
    <span class="dialog-footer">
      <el-button @click="resetPwdDialogVisible = false" >&nbsp;取消&nbsp;</el-button>
      <el-button type="primary" @click="confirmResetPassword">&nbsp;确定重置&nbsp;</el-button>
    </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { getUUID } from "@/api/Coach.js";
import {updateCoachQrcode} from "@/api/Coach.js";
import {updateCoachLogo} from "@/api/Coach.js";
import { getOneCoachInfo } from "@/api/Coach.js";
import { updateCoach } from "@/api/Coach.js";
import {getRegionList} from "@/api/Coach.js";
import Sidebar from '@/components/Sidebar.vue';
import {ref, onMounted} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus'
import {getCoaches} from "@/api/Coach.js";
import {useRouter} from 'vue-router';

const selectedSortBy = ref('activity_level');
const selectedSortOrder = ref('desc');
const router = useRouter();
const CoachesList = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const loading = ref(false);
const maxActivityRef = ref(0);
const totalCoachesList = ref([]);
const formatCreateTime = (timeStr) => {
  if (!timeStr) return '';
  return timeStr.split('T')[0];
};

const formatDate = (timeStr) => {
  if (!timeStr) return '未设置';
  const date = new Date(timeStr);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

//uuid
import { CopyDocument, Check } from '@element-plus/icons-vue';
const copyUUID = async () => {
  if (!editForm.value.uuid) {
    ElMessage.warning('UUID为空，无法复制');
    return;
  }

  const uuid = `https://xjg.tongguantech.cn/bindingcoach.html?token=${editForm.value.uuid}`;

  try {
    await navigator.clipboard.writeText(uuid);
    copyStatus.value = 'copied';
    ElMessage.success('UUID已复制到剪贴板');
    setTimeout(() => {
      copyStatus.value = 'copy';
    }, 2000);
  } catch (error) {
    ElMessage.error('复制失败，请手动复制');
  }
};
const copyStatus = ref('copy');

//修改logo
import { Plus } from '@element-plus/icons-vue';
const tempLogoUrl = ref('');
const isUploading = ref(false);
const beforeUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng)
  {
    ElMessage.error('只能上传JPG/PNG格式的图片');
    return false;
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB');
    return false;
  }
  return true;
};
const customLogoUpload = async (params) => {
  if (!editCoachId.value)
  {
    ElMessage.error('教练ID不存在，无法上传');
    params.onError();
    return;
  }
  isUploading.value = true;
  try
  {
      const formData = new FormData();
      formData.append('file', params.file);
      const response = await updateCoachLogo(editCoachId.value, formData);
      if (response.status === 1 && response.content === 'success')
      {
        params.onSuccess(response);
        return response;
      }
      else
      {
        throw new Error(response.content || 'LOGO上传失败');
      }
  }
  catch (error)
  {
      ElMessage.error(error.message || '上传失败，请重试');
      params.onError();
  }
  finally
  {
      isUploading.value = false;
  }
};
const handleLogoUploadSuccess = (response) => {

  if (!response || response.status !== 1)
  {
    ElMessage.error('LOGO上传失败，请重试');
    return;
  }
  const newLogoUrl = response.data;
  if (newLogoUrl)
  {
    tempLogoUrl.value = newLogoUrl;
    editForm.value.logo = newLogoUrl;
  }
  else
  {
    ElMessage.warning('未获取到LOGO地址，将刷新显示');
    getOneCoachInfo(editCoachId.value).then(detail => {
      if (detail.status === 1) {
        editForm.value.logo = detail.data.logo;
        tempLogoUrl.value = detail.data.logo;
      }
    });
  }
};


//修改二维码
const qrcodeUploadRef = ref(null);
const tempQrcodeUrl = ref('');
const handleQrcodeUploadSuccess = (response) => {

  if (!response || response.status !== 1)
  {
    ElMessage.error('二维码上传失败，请重试');
    return;
  }
  const newQrcodeUrl = response.data;
  if (newQrcodeUrl)
  {
    tempQrcodeUrl.value = newQrcodeUrl;
    editForm.value.qrCode = newQrcodeUrl;
  }
  else
  {
    ElMessage.warning('未获取到二维码地址，将刷新显示');
    getOneCoachInfo(editCoachId.value).then(detail => {
      if (detail.status === 1) {
        editForm.value.qrcode = detail.data.qrCode;
        tempQrcodeUrl.value = detail.data.qrCode;
      }
    });
  }
};
const customQrcodeUpload = async (params) => {
  if (!editCoachId.value)
  {
    ElMessage.error('教练ID不存在，无法上传');
    params.onError();
    return;
  }
  isUploading.value = true;
  try
  {
    const formData = new FormData();
    formData.append('file', params.file);
    const response = await updateCoachQrcode(editCoachId.value, formData);
    if (response.status === 1 && response.content === 'success')
    {
      params.onSuccess(response);
      return response;
    }
    else
    {
      throw new Error(response.content || '二维码上传失败');
    }
  }
  catch (error)
  {
    ElMessage.error(error.message || '上传失败，请重试');
    params.onError();
  }
  finally
  {
    isUploading.value = false;
  }
};

const open = async (rowData) => {
  const detailResponse = await getOneCoachInfo(rowData.id);

  if (detailResponse.status !== 1 || detailResponse.content !== "success")
  {
    ElMessage.error('获取详情失败');
    return;
  }
  const coachDetail = detailResponse.data;
  const fieldMap = {
    username: '姓名',
    phone: '手机号',
    lastLoginTime: '上次登陆时间',
    createTime: '创建时间',
    slogan: '口号',
    schoolName: '驾校名称',
    validTime: '有效期',
    activity: '活动数',
    isBelongWithAdmin: '是否属于管理员',
    regionCode: '地区代码',
    regionName:'地区',
    notes: '备注',
    isStreamer: '是否主播',
    qrCode: '二维码',
    ratio: '分成比例',
    coachId:'教练编号'
  };
  const avatarUrl = coachDetail.logo;
  const imageContent = `
    <div style="text-align: center; margin-bottom: 15px;">
      <img
        src="${avatarUrl}"
        alt="未设置"
        style="width: 120px; height: 120px; border-radius: 50%; object-fit: cover; border: 2px solid #eee;"
      >
    </div>
  `;

  let detailContent = `<div class="detail-container">${imageContent}`;

  for (const key in coachDetail) {
    if (key === 'logo') continue;
    const displayKey = fieldMap[key] || key;
    let displayValue;

    if (key === 'regionName') {
      displayValue = coachDetail[key] || '未设置地区';
    }
    else if (key === 'regionCode') {
      displayValue = coachDetail[key] || '无地区代码';
    }

    if (key === 'qrCode')
    {
      if (coachDetail[key])
      {
        displayValue = `<img src="${coachDetail[key]}" alt="无" style="width: 150px; height: 150px; margin-top: 10px;">`;
      } else
      {
        displayValue = '未生成二维码';
      }
    }
    else if (key === 'isBelongWithAdmin')
    {
      if (coachDetail[key] === null || coachDetail[key] === undefined)
      {
        displayValue = '未设置';
      }
      else
      {
        displayValue = coachDetail[key] ? '是' : '否';
      }
    }
    else if (key === 'isStreamer')
    {
      if (coachDetail[key] === null || coachDetail[key] === undefined)
      {
        displayValue = '未设置';
      }
      else
      {
        displayValue = coachDetail[key] ? '是' : '否';
      }
    }
    else if (['lastLoginTime', 'validTime', 'createTime'].includes(key))
    {
      displayValue = formatDate(coachDetail[key]);
    }
    else
    {
      displayValue = coachDetail[key] || '未设置';
    }


    detailContent += `
      <div class="detail-row" style="margin: 15px 0;">
        <span class="detail-key" style="display: inline-block; width: 100px; font-weight: 500;">
          ${displayKey}：
        </span>
        <span class="detail-value">${displayValue}</span>
      </div>
    `;
  }
  detailContent += '</div>';
  ElMessageBox.alert(
      detailContent,
      '教练详情',
      {
        confirmButtonText: 'OK',
        dangerouslyUseHTMLString: true,
        customClass: 'student-detail-dialog',
        width: '600px'
      }
  );
};


const searchForm = ref({
  keyword: '',
  currentPage: 1,
  pageSize: 10,
  sortBy: 'activity_level',
  sortOrder: 'desc',
});


onMounted(() => {
  fetchCoaches();
  fetchRegionList();
});

const calculateActivityPercentage = (activityCount) => {
  if (!activityCount || activityCount <= 0) return 0;
  return Math.round((activityCount / maxActivityRef.value) * 100);
};

const getStatus = (activityCount) => {
  if (!activityCount || activityCount <= 0) return 'info';
  if (activityCount < 20) return 'warning';
  if (activityCount < 40) return 'success';
  return 'success';
};

const fetchCoaches = async () => {
  loading.value = true;
  try {
    searchForm.value.currentPage = currentPage.value;
    searchForm.value.pageSize = pageSize.value;

    const response = await getCoaches(
        {
          keyword: searchForm.value.keyword,
          currentPage: searchForm.value.currentPage,
          pageSize: searchForm.value.pageSize,
          sortBy: searchForm.value.sortBy,
          sortOrder: searchForm.value.sortOrder,
        }
    );

    if (response.status === 1 && response.content === "success") {
      response.data.data.forEach(item => {
        if (!totalCoachesList.value.some(existItem => existItem.id === item.id)) {
          totalCoachesList.value.push(item);
        }
      });
      CoachesList.value = response.data.data || [];
      total.value = response.data.total || 0;
      if (totalCoachesList.value.length > 0) {
        maxActivityRef.value = Math.max(
            ...totalCoachesList.value.map(item => item.activity || 0)
        );
      }

    } else {
      ElMessage.error('获取教练列表失败');
    }
  } catch (error) {
    ElMessage.error('网络错误，请重试');
    router.push('/login');
  } finally {
    loading.value = false;
  }
};

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  currentPage.value = 1;
  fetchCoaches();
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  fetchCoaches();
};

const handleSortTypeChange = (sortBy) => {
  selectedSortBy.value = sortBy;
  searchForm.value.sortBy = sortBy;
  searchForm.value.sortOrder = selectedSortOrder.value;
  fetchCoaches();
};


// 处理排序变化
const handleSortChange = ({ prop, order }) => {
  const sortMap = {
    'createTime': 'create_time',
    'activity':'activity_level'
  };

  const orderMap = {
    'ascending': 'asc',
    'descending': 'desc'
  };

  searchForm.value.sortBy = sortMap[prop] || 'create_time';
  searchForm.value.sortOrder = orderMap[order] || 'desc';

  fetchCoaches();
};

//修改详情
const editDialogVisible = ref(false);
const editForm = ref({
  uuid: ''
});
const editCoachId = ref(null);
const initialEditForm = ref({});

const resetEditForm = () => {
  editForm.value = {};
  editCoachId.value = null;
};

const editCoach = async (row) => {
  loading.value = true;
  try {
      const detailResponse = await getOneCoachInfo(row.id);
      if (detailResponse.status === 1)
      {
        editForm.value = {...row,...detailResponse.data };
        handleRegionChange(editForm.value.regionCode);
        const uuidResponse = await getUUID(row.id);
        if (uuidResponse.status === 1)
        {
          editForm.value.uuid = uuidResponse.data.token;
        }
        else
        {
          ElMessage.warning('获取UUID失败');
          editForm.value.uuid = '获取失败';
        }
        tempLogoUrl.value = '';
        tempQrcodeUrl.value = '';
        editDialogVisible.value = true;
        editCoachId.value = row.id;
        initialEditForm.value = {...editForm.value };
      }
  }
  catch (error)
  {
      ElMessage.error('加载编辑信息失败');
      console.error(error);
  }
  finally
  {
      loading.value = false;
  }
};

const beforeCloseEditDialog = () => {

  if (tempLogoUrl.value) {
    URL.revokeObjectURL(tempLogoUrl.value);
  }
  if (tempQrcodeUrl.value) {
    URL.revokeObjectURL(tempQrcodeUrl.value);
  }

  tempLogoUrl.value = '';
  tempQrcodeUrl.value = '';

  editForm.value = {...initialEditForm.value };
};


const saveCoach = async () => {
  if (!editCoachId.value) {
    ElMessage.error('教练ID不能为空');
    return;
  }

  try {
    loading.value = true;
    let formattedValidTime = null;

    if (editForm.value.validTime) {
      const datePart = editForm.value.validTime.split('T')[0]; // 提取日期部分
      formattedValidTime = `${datePart}T00:00:00.000`; // 固定时间部分为 00:00:00
    }

    const basicData = {
      coachId: editCoachId.value,
      username: editForm.value.username,
      phone: editForm.value.phone,
      slogan: editForm.value.slogan,
      schoolName: editForm.value.schoolName,
      validTime: formattedValidTime,
      ratio: editForm.value.ratio,
      isBelongWithAdmin: editForm.value.isBelongWithAdmin,
      isStreamer: editForm.value.isStreamer,
      notes: editForm.value.notes,
      regionCode: editForm.value.regionCode,
    };
    const basicResponse = await updateCoach(basicData);
    console.log("basicResponse",basicResponse);
    if (basicResponse.status !== 1 || basicResponse.content !== "success") {
      ElMessage.error('信息更新失败: ' + (basicResponse.content || '系统错误'));
      return;
    }
    editDialogVisible.value = false;
    fetchCoaches();
  }
  catch (error)
  {
    console.error('更新请求错误:', error.response?.data || error.message);
    ElMessage.error('更新失败: 网络错误');
  }
  finally
  {
    loading.value = false;
  }
};

//修改密码
import {  reactive } from 'vue';
import md5 from 'js-md5';
import { changeCoachPassword } from '@/api/Coach.js';

const resetPwdDialogVisible = ref(false);
const currentCoachId = ref('');
const resetPwdForm = reactive({
  newPassword: '',
  confirmPassword: ''
});

const resetPwdRules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度需在6-20位之间', trigger: 'blur' },
    {
      pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,20}$/,
      message: '密码需包含字母和数字',
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== resetPwdForm.newPassword)
        {
          callback(new Error('两次输入的密码不一致'));
        }
        else
        {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
};

const resetPwdFormRef = ref(null);

const resetPassword = (row) => {
  currentCoachId.value = row.id;
  resetPwdForm.newPassword = '';
  resetPwdForm.confirmPassword = '';
  resetPwdDialogVisible.value = true;
};

const confirmResetPassword = async () => {
  if (!resetPwdFormRef.value) return;
  const valid = await resetPwdFormRef.value.validate();
  if (!valid) return;

  try {

    const encryptedPassword = md5(resetPwdForm.newPassword);

    const response = await changeCoachPassword({
      id: currentCoachId.value,
      password: encryptedPassword
    });
    if (response.status === 1 && response.content === 'success')
    {
      ElMessage.success('密码重置成功');
      resetPwdDialogVisible.value = false;
    }
    else
    {
      ElMessage.error(`重置失败：${response.content || '未知错误'}`);
    }
  }
  catch (error)
  {
    console.error('密码重置请求失败：', error);
    ElMessage.error('网络错误，重置失败');
  }
};

//修改地区

const regionList = ref([]);
const currentRegionName = ref('');
const loadingRegion = ref(false);


const fetchRegionList = async () => {
  loadingRegion.value = true;
  try {
    const response = await getRegionList();
    if (response.status === 1 && response.content === "success") {
      regionList.value = response.data || [];
    } else {
      ElMessage.error('获取地区列表失败: ' + (response.content || '系统错误'));
    }
  } catch (error) {
    console.error('获取地区列表错误:', error);
    ElMessage.error('网络错误，无法加载地区列表');
  } finally {
    loadingRegion.value = false;
  }
};

const handleRegionChange = (code) => {
  if (!code) {
    currentRegionName.value = '';
    return;
  }
  const selectedRegion = regionList.value.find(r => r.regionCode === code);
  currentRegionName.value = selectedRegion ? selectedRegion.name : '';
  editForm.value.regionName = currentRegionName.value;
};




</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html, body {
  padding: 0;
  margin: 0;
  height: 100vh;
  width: 100vh;
}

.all {
  width: 100%;
  height: 100%;
}

.all_content {
  display: flex;
  height: 100vh;
  width: 100%;
}

.all_main {
  width: 100vh;
  padding: 0px;
  margin: 0px;
}

.head {
  width: 100%;
  height: 4vh;
  display: flex;
  align-items: center;
  border-bottom: solid 1px rgba(204, 204, 204, 0.66);
}

.main {
  width: 100%;
}

.item {
  padding-left: 30px;
}

.t {
  color: #090909;
  font-size: 18px;
  font-weight: 500;
}

.s {
  display: flex;
}

.search-area {
  justify-content: center;
  gap: 10px;
  align-items: center;
  width: 1000px;
  margin: 20px auto;
}

.table-wrapper {
  display: flex;
  justify-content: center;
  overflow-x: auto;
}
.pagination {
  display: flex;
  justify-content: center;
  font-family:"Times New Roman" ;
}


</style>

